///////////////////////////////////////////////// timeline library//////////////////////////////////
// ref : http://almende.github.io/chap-links-library/js/timeline/doc/

////////////////////////////////////////////////////////////////////////////////////////////////
// flag for memorizing user's behavior 
var color_selected;
var evtBtn_selected=false;
var mouseOverCounter=0;
var adjFlag;
var disableCounter=0;
var mDate;
var fetchedDate;





/*
@purpose: given the json result generated by function "fetchSelectedTimeRegions", user call
          this function to reproduce the GUI input from end user
*/

var copyCurrentSchedule2Tmr=function(){
    var jsonArray=fetchSelectedTimeRegions();

    var disableInput=jsonArray.disable;
  if(disableInput==="on"){
    $("#cancel").button('toggle');
    $("#cancel").button('complete');
  }

  if(disableInput==="off"){
    $("#cancel").button('reset');
  }


  var spInput=jsonArray.sp;
  if(spInput==="on"){
   $("#sp_on").attr('checked', true);
 }

 if(spInput==="off"){
   $("#sp_off").attr('checked', true);
 }

 if(spInput==="none"){
   $("#sp_off").attr('checked', false);
   $("#sp_on").attr('checked', false);
 }

 var evtNameArray=[];
 for(var i=0;i<jsonArray.events.length;i++){
  var start=eval(jsonArray.events[i].start_time.split("")[0]+jsonArray.events[i].start_time.split("")[1]);
  var end=eval(jsonArray.events[i].end_time.split("")[0]+jsonArray.events[i].end_time.split("")[1]);
  var numOfThisEvent=end-start;

  if(numOfThisEvent<=0){
   numOfThisEvent=24+numOfThisEvent;
 }

 

 for(var j=0;j<numOfThisEvent;j++){

  evtNameArray.push(jsonArray.events[i].event_name);
}

}

var currentDate=jsonArray.date; 
var nextDate=currentDate.addDays(1);

$("#headerDate").text(nextDate.toFormat('DDDD'));
drawVisualization(nextDate,evtNameArray);



};


/*
@purpose: given the json result generated by function "fetchSelectedTimeRegions", user call
          vizJsonResult to reproduce the GUI input from end user

@param jsonArray:json result generated by function "fetchSelectedTimeRegions"

*/


var vizJsonResult=function(jsonArray){
  var disableInput=jsonArray.disable;
  if(disableInput==="on"){
    $("#cancel").button('toggle');
    $("#cancel").button('complete');
  }

  if(disableInput==="off"){
    $("#cancel").button('reset');
  }


  var spInput=jsonArray.sp;
  if(spInput==="on"){
   $("#sp_on").attr('checked', true);
 }

 if(spInput==="off"){
   $("#sp_off").attr('checked', true);
 }

 if(spInput==="none"){
   $("#sp_off").attr('checked', false);
   $("#sp_on").attr('checked', false);
 }

 var evtNameArray=[];
 for(var i=0;i<jsonArray.events.length;i++){
  var start=eval(jsonArray.events[i].start_time.split("")[0]+jsonArray.events[i].start_time.split("")[1]);
  var end=eval(jsonArray.events[i].end_time.split("")[0]+jsonArray.events[i].end_time.split("")[1]);
  var numOfThisEvent=end-start;

  if(numOfThisEvent<=0){
   numOfThisEvent=24+numOfThisEvent;
 }



 for(var j=0;j<numOfThisEvent;j++){

  evtNameArray.push(jsonArray.events[i].event_name);
}

}

yourDate=jsonArray.date; 


$("#headerDate").text(yourDate.toFormat('DDDD'));
drawVisualization(yourDate,evtNameArray);

}


// jquery function for centering html element at the center of the screen
jQuery.fn.center = function ()
{
  this.css("position","fixed");
  this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
  return this;
};


/*function for merging continuous schedule with the same type of event,
  use in fetchSelectedTimeRegions
  @param jsonArray: defined as variable "result" in function "fetchSelectedTimeRegions"
  */

  var mergeContiEvent=function(jsonArray){
   var result_merged=[];
   var isFinalBlockMerged=false;

   for(var i=0;i<jsonArray.length;i++){

     var currentEventType=jsonArray[i].eventType;
     var currentEventName=jsonArray[i].event_name; 
     var start=jsonArray[i].start_time;    
     var end=jsonArray[i].end_time;
     if(i==jsonArray.length-1 && !isFinalBlockMerged){
      result_merged.push({start_time:start,end_time:end,event_type:currentEventType,event_name:currentEventName});
    }
    if(i!=(jsonArray.length-1)){
     for(var j=i+1;j<jsonArray.length;j++){
       if(currentEventType!=jsonArray[j].eventType){
        result_merged.push({start_time:start,end_time:end,event_type:currentEventType,event_name:currentEventName});
        i=j-1;
        break;
      }

      else{
        end=jsonArray[j].end_time;
        if(j==jsonArray.length-1){
         isFinalBlockMerged=true;    
         result_merged.push({start_time:start,end_time:end,event_type:currentEventType,event_name:currentEventName});
         i=j-1;
       }

     }
   } 

 }
}


return result_merged;

}
// function for fetching schedule arrange by end user
var fetchSelectedTimeRegions=function(){
    // grab the today's info
    var now=new Date();
    var now_year=now.getFullYear();
    var now_date=now.getDate();
    var now_month=now.getMonth()+1;


    var allregions=$('.bar');
    var allTags=$('.timeline-axis-text-minor');
    var result=[];
    
    for(var j=0;j<allregions.length;j++){
        // on events
        if(allregions[j].style.background.indexOf("rgb(81, 163, 81)")>=0 ||allregions[j].style.backgroundColor.indexOf("rgb(81, 163, 81)")>=0){

         result.push({start_time:allTags[j+3].textContent,end_time:allTags[j+4].textContent,eventType:"on", event_name:"0"});

       }

        // off events
        if(allregions[j].style.background.indexOf("rgb(0, 68, 204)")>=0 ){
         result.push({start_time:allTags[j+3].textContent,end_time:allTags[j+4].textContent,eventType:"off",event_name:"1"});              
       }

       if(allregions[j].style.background.indexOf("rgb(248, 148, 6)")>=0 ){
         result.push({start_time:allTags[j+3].textContent,end_time:allTags[j+4].textContent,eventType:"off",event_name:"2"});              
       }

       if(allregions[j].style.background.indexOf("rgb(235, 0, 255)")>=0 ){

         result.push({start_time:allTags[j+3].textContent,end_time:allTags[j+4].textContent,eventType:"off",event_name:"3"});               
       }



     }   


    // fetching sp on/off values selected by end-user
    var radioValue=$("[type=radio]:checked").val();
    if(radioValue===undefined){
     radioValue="none";
   }

    // fetching value of disable button
    var disableVal=$("#cancel").text();
    if(disableVal=="Disabled !!!"){
      disableVal="on";
    }

    if(disableVal=="Disable"){
      disableVal="off";
    }

    
    var result_final={ 
     date:mDate,
     sp:radioValue,
     disable:disableVal,
     events:mergeContiEvent(result)

   };



   return result_final;
 }; 


 var transformDateInJson4III=function(jsonObj){
  var day_obj=jsonObj.date.toFormat('DDDD');
  jsonObj.date=day_obj;
  delete(jsonObj.date);
  jsonObj.day=day_obj;
  return jsonObj;

}



// make colors of adjacent off event identical, if set different by user
var mergeAdjacentOff=function(){
 var allBars=$('.bar');
 var offFlagPattern=/offFlag/;
 for(var i=0;i<allBars.length;i++){
   if(offFlagPattern.test(allBars[i].className)){

    if(i>0 && offFlagPattern.test(allBars[i-1].className)){


     if(allBars[i].style.background!=allBars[i-1].style.background){
      allBars[i].style.background=allBars[i-1].style.background;

    }
  }
}          
}
};

$(document).ready(function($) {
     
       // add the day between two arrows
       var today=Date.today();
       // variable for calculate the day set by end-user
       mDate=Date.today();

       $("#rightArrow").before("<span id='headerDate'>"+today.toFormat('DDDD')+"</span>"+"&nbsp;&nbsp;");

       //SP Off Button will refresh the scheduler bar
       $("#sp_off").click(function() {
         var bars=$('.bar');
         for(var idx=0; idx<bars.length; idx++){
           var bar=bars[idx];
           bar.style.backgroundColor="rgb(81, 163, 81)";


         }
         
            
          });


       // cancel button will refresh the web page 
       $("#cancel").click(function() {
          // console.log('here');
          disableCounter=disableCounter+1;
          if(disableCounter%2==1){
            $(this).button('toggle');
            $(this).button('complete');
          }

          else{
            $(this).button('reset');
          }

           //location.reload(true);
         }
         );


       $("#save").click(function(){
        mergeAdjacentOff();
        fetchSelectedTimeRegions(); 
        $('<a  id="copy2Tmr" class="btn btn-danger" onclick="copyCurrentSchedule2Tmr()">Copy to next scheduler</a>').appendTo('.pageaction');
        alert("Please see call function fetchSelectedTimeRegions to see the data objects selected");

      }
      );

       // for displaying tooltips
       $(".btn").mouseenter(function(){
         $('<p id="btn_tooltip">left-mouse click to add schedule, right-mouse click to remove , adjacent off events will be merged at saving</p>').appendTo('#tooltip');
       }).mouseleave(function(){
        $('#btn_tooltip').remove();
        
      });
       
       

      // positioning date selector
      $("#date_modifier").center();

      $("#spWidget").position({
        my: "right top",
        at: "right top",
        of: "body"
      });
      $(window).resize(function(){
        $('#date_modifier').center();
        
      });

       //  for user to arrange scheduler ahead of today
       $("#rightArrow").click(function(){
            // generation of new timeline
            console.log('right arrow clicked');
            mDate=mDate.addDays(1);
            $("#cancel").button('reset');
            $("#sp_off").attr('checked', false);
            $("#sp_on").attr('checked', false);
            drawVisualization(mDate,undefined);

            // update the day information
            $("#headerDate").text(mDate.toFormat('DDDD'));
          });




      // for user to arrange scheduler prior to today
      $("#leftArrow").click(function(){
        console.log('left arrow clicked');
            // generation of new timeline
            mDate=mDate.addDays(-1);
            $("#cancel").button('reset');
            $("#sp_off").attr('checked', false);
            $("#sp_on").attr('checked', false);
            drawVisualization(mDate,undefined);
            
            // update the day information
            $("#headerDate").text(mDate.toFormat('DDDD'));

          });


       // to interaction for toggle-switch button
       $('.switch').on('switch-change', function (e, data) {

          // on-event
          if(data.value===true){
              var patt_off=/off/;
              var patt_on=/on/;

              $('.bar').off();
      

              $('.bar').mousedown(function(event){
              
       
                $(this).css('background','rgb(81, 163, 81)');

                if(adjFlag==="onFlag"){
                 $(this).removeClass("offFlag");
               }

               else{
                $(this).removeClass("onFlag");
              }

              $(this).addClass(adjFlag);

              $('.bar').mouseover(function(){
                $(this).css('background','rgb(81, 163, 81)');

                if(adjFlag==="onFlag"){
                 $(this).removeClass("offFlag");
               }

               else{
                $(this).removeClass("onFlag");
              }

              $(this).addClass(adjFlag);
                      
                     });

              $('.timeline-axis').mouseenter(function(){
                $('.bar').off('mouseover');
                      
                      }).mouseup(function(){
                       console.log('mouseup');
                       $('.bar').off('mouseover');
                       $('.timeline-axis').off('mouseenter');
                   
                  }

                  );

              
                
              }).mouseup(function(){
               console.log('mouseup');
               $('.bar').off('mouseover');
               $('.timeline-axis').off('mouseenter');

             });

          }
          
          // off-event
          else{
            
              var patt_off=/off/;
              var patt_on=/on/;

              $('.bar').off();
      

              $('.bar').mousedown(function(event){
              
       
                $(this).css('background','rgb(0, 68, 204)');

                if(adjFlag==="onFlag"){
                 $(this).removeClass("offFlag");
               }

               else{
                $(this).removeClass("onFlag");
              }

              $(this).addClass(adjFlag);

              $('.bar').mouseover(function(){
                $(this).css('background','rgb(0, 68, 204)');

                if(adjFlag==="onFlag"){
                 $(this).removeClass("offFlag");
               }

               else{
                $(this).removeClass("onFlag");
              }

              $(this).addClass(adjFlag);
                       
                     });

              $('.timeline-axis').mouseenter(function(){
                $('.bar').off('mouseover');
                       
                      }).mouseup(function(){
                       console.log('mouseup');
                       $('.bar').off('mouseover');
                       $('.timeline-axis').off('mouseenter');
                  
                  }

                  );

              
                
              }).mouseup(function(){
               console.log('mouseup');
               $('.bar').off('mouseover');
               $('.timeline-axis').off('mouseenter');

             });



         } 


       });

});